<template>
  <div class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="工艺要求编码" prop="code">
          <CodeRuleInput :band-value.sync="formData.code" table-name="engineering_requirement" column-name="code" :is-edit="tagId" />
        </el-form-item>
        <el-form-item label="物料编码" class="clickChoose" prop="materialCode">
          <el-input v-model="formData.materialCode" placeholder="请选择" readonly />
          <a
            class="clickChoose_button"
            @click.prevent="chooseMaterial"
          >
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="formData.materialName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="规格型号" prop="materialModel">
          <el-input v-model="formData.materialModel" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="物料分类" prop="materialTypeName">
          <el-input v-model="formData.materialTypeName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="物料单位" prop="materialUnitName">
          <el-input v-model="formData.materialUnitName" placeholder="暂无" disabled />
        </el-form-item>

        <!-- <el-form-item label="工艺流程号" class="clickChoose" prop="flowCode">
          <el-input v-model="formData.flowCode" placeholder="请选择" readonly />
          <a
            class="clickChoose_button"
            @click.prevent="chooseProcessFlow"
          >
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item> -->
        <el-form-item label="版本号" prop="versionCode">
          <el-input v-model="formData.versionCode" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="计划单状态限制" prop="isEqual" class="double">
          <el-radio-group v-model="formData.isEqual">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
          <span style="color: #CCCCCC;">（如果选择是，则计划数量必须等于生产数量才能完成； 如果选择否，则计划单可以随时完成或终止）</span>
        </el-form-item>
        <el-form-item label="附件" class="double">
          <FileManageFull
            :file-names="formData.fileName"
            :file-real-names="formData.fileRealName"
            :file-urls="formData.fileUrl"
            :row-index="1"
            @fileName="setFileName"
          />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div v-if="formData.materialName" class="processRequirement_bottom">
        <div class="processRequirement_bottom_tree">
          <div class="tree_header">物料</div>
          <div class="tree_container">
            <el-tree
              ref="tree"
              :data="treeData"
              node-key="nodeKey"
              :expand-on-click-node="false"
              :default-expand-all="true"
              :highlight-current="true"
              :default-checked-keys="checkedKeys"
              @node-click="treeNodeClick"
            >
              <div slot-scope="{ node, data }" class="tree-node">
                {{ data.materialCode }}/{{ data.materialName }}
              </div>
            </el-tree>
          </div>
          <!-- <div class="tree_container">
            <a
              v-for="(item,index) in processFlowList"
              :key="index"
              class="tree_container_item"
              :class="currentProcess.processFlowDetailId==item.processFlowDetailId?'selected_row':''"
              @click="processClick(item,index)"
            >
              {{ item.wayName }}
            </a>
          </div> -->
        </div>
        <div v-if="isShow" class="processRequirement_bottom_detail">
          <div class="formItem_header">
            {{ currentNodeData.currentmaterial }}工艺要求
          </div>
          <div class="detail_form">
            <div class="detail_form_item" style="width:100%">
              <div class="detail_form_item_name" :class="[tableData1&&tableData1.length==0?'':'bitian']">工序</div>
              <div class="clickChoose">
                <el-input v-model="engineeringProcessName" placeholder="请选择" readonly />
                <a
                  class="clickChoose_button"
                  @click.prevent="chooseProcess"
                >
                  <svg-icon icon-class="选择弹框" />
                </a>
              </div>
            </div>
            <div class="detail_form_item_double">
              <div class="detail_form_item_name bitian">标记工序</div>
              <div class="detail_form_item_radio">
                <el-radio-group v-model="productBySelf" @change="(e)=>{currentNodeData.productBySelf=e}">
                  <el-radio label="1">自己生产</el-radio>
                  <el-radio label="0">外协</el-radio>
                </el-radio-group>
              </div>
            </div>
            <div class="detail_form_item">
              <div class="detail_form_item_name bitian">是否送检</div>
              <div class="detail_form_item_radio">
                <el-radio-group v-model="toInspect" @change="(e)=>{currentNodeData.toInspect=e}">
                  <el-radio label="1">送检</el-radio>
                  <el-radio label="0">不送检</el-radio>
                </el-radio-group>
              </div>
            </div>
            <div class="detail_form_item">
              <div class="detail_form_item_name bitian">是否入库</div>
              <div class="detail_form_item_radio">
                <el-radio-group v-model="toWms" @change="(e)=>{currentNodeData.toWms=e}">
                  <el-radio label="1">入库</el-radio>
                  <el-radio label="0">不入库</el-radio>
                </el-radio-group>
              </div>
            </div>
          </div>
          <div class="formItem_header formItem_header_padding">
            计时
          </div>
          <div class="detail_form">
            <div class="detail_form_item">
              <div class="detail_form_item_name">标准工时（时）</div>
              <div class="detail_form_item_input">
                <el-input v-model="currentNodeData.standardWorkTime" placeholder="请输入" clearable />
              </div>
            </div>
            <div class="detail_form_item">
              <div class="detail_form_item_name">工时单价（元）</div>
              <div class="detail_form_item_input">
                <el-input v-model="currentNodeData.workTimePrice" placeholder="请输入" clearable />
              </div>
            </div>
          </div>
          <div class="formItem_header formItem_header_padding">
            计件
          </div>
          <div class="detail_form">
            <div class="detail_form_item">
              <div class="detail_form_item_name">计件单价（元）</div>
              <div class="detail_form_item_input">
                <el-input v-model="currentNodeData.unitPriceOfPiecework" placeholder="请输入" clearable />
              </div>
            </div>
          </div>
          <div class="formItem_header formItem_header_padding">
            生产输入
            <div class="formItem_header_operate">
              <a class="formItem_header_operate_item" @click="chooseProduceIn">
                <svg-icon icon-class="新增" />
                <div class="item_name">添加</div>
              </a>
              <a class="formItem_header_operate_item delete" @click="deleteProduceIn">
                <svg-icon icon-class="删除" />
                <div class="item_name">删除</div>
              </a>
            </div>
          </div>
          <div ref="table_container" class="table_container">
            <el-table
              ref="table"
              :data="tableData1"
              stripe
              border
              :header-cell-class-name="headerCellClassName"
              @selection-change="selectionChange1"
            >
              <el-table-column type="selection" width="70" align="center" />
              <el-table-column label="物料编码" min-width="120" prop="materialCode" :show-overflow-tooltip="true" />
              <el-table-column label="物料名称" min-width="100" prop="materialName" :show-overflow-tooltip="true" />
              <el-table-column label="规格型号" min-width="100" prop="materialModel" :show-overflow-tooltip="true" />
              <el-table-column label="物料分类" min-width="100" prop="materialTypeName" :show-overflow-tooltip="true" />
              <el-table-column label="物料单位" min-width="100" prop="materialUnitName" :show-overflow-tooltip="true" />
              <el-table-column label="备注" :min-width="SETTINGS.settings_decimalDigits_length" prop="remark">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.remark"
                    clearable
                    placeholder="请输入"
                  />
                </template>
              </el-table-column>
              <el-table-column label="领退料限制" :min-width="SETTINGS.settings_decimalDigits_length" fixed="right" prop="requisitionOrReturnList">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.requisitionOrReturn" placeholder="请选择">
                    <el-option
                      v-for="item in requisitionOrReturnList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="需求数量" :min-width="SETTINGS.settings_decimalDigits_length" fixed="right" prop="demandNumber">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.demandNumber"
                    clearable
                    placeholder="请输入"
                  />
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="formItem_header formItem_header_padding">
            生产输出
            <div class="formItem_header_operate" />
          </div>

          <div ref="table_container" class="table_container">
            <el-table
              ref="table2"
              :data="tableData2"
              stripe
              border
              :header-cell-class-name="headerCellClassName"
            >
              <el-table-column label="物料编码" min-width="120" prop="materialCode" :show-overflow-tooltip="true" />
              <el-table-column label="物料名称" min-width="100" prop="materialName" :show-overflow-tooltip="true" />
              <el-table-column label="规格型号" min-width="100" prop="materialModel" :show-overflow-tooltip="true" />
              <el-table-column label="物料分类" min-width="100" prop="materialTypeName" :show-overflow-tooltip="true" />
              <el-table-column label="物料单位" min-width="100" prop="materialUnitName" :show-overflow-tooltip="true" />
              <el-table-column label="产出数量" :min-width="SETTINGS.settings_decimalDigits_length" prop="outputNumber">
                <template slot-scope="scope">
                  <span>1</span>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="formItem_header formItem_header_padding">
            生产过程
            <div class="formItem_header_operate">
              <a class="formItem_header_operate_item" @click="chooseProduceProcess">
                <svg-icon icon-class="新增" />
                <div class="item_name">添加</div>
              </a>
              <a class="formItem_header_operate_item delete" @click="deleteProduceProcess">
                <svg-icon icon-class="删除" />
                <div class="item_name">删除</div>
              </a>
            </div>
          </div>

          <div ref="table_container" class="table_container">
            <el-table
              ref="table3"
              :data="currentNodeData.engineeringRequirementProcess"
              stripe
              border
              @selection-change="selectionChange3"
            >
              <el-table-column type="selection" width="70" align="center" />
              <el-table-column label="操作描述">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.operationDescription"
                    clearable
                    placeholder="请输入"
                  />
                </template>
              </el-table-column>
              <el-table-column label="产品特性">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.productCharacter"
                    clearable
                    placeholder="请输入"
                  />
                </template>
              </el-table-column>
              <el-table-column label="过程特性">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.courseCharacter"
                    clearable
                    placeholder="请输入"
                  />
                </template>
              </el-table-column>
              <el-table-column label="图号">
                <template slot-scope="scope">
                  <FileManage
                    :file-names.sync="scope.row.fileName"
                    :file-real-names.sync="scope.row.fileRealName"
                    :file-urls.sync="scope.row.fileUrl"
                    :row-index="scope.$index"
                    @fileName="setFileName2"
                  />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit('0')">保存</el-button>
      <el-button @click.stop="onSubmit('1')">提交</el-button>
    </div>
  </div>
</template>

<script>
import { addOrEdit, addOrUpdate, getInfo, getInfoYg } from '@/api/engineeringManage/processRequirementNew'
import { getInfo as getProcessList } from '@/api/engineeringManage/processFlow'
import chooseMaterial from './chooseMaterial.vue'
import ChooseProcessFlow from '@/views/engineeringManage/processFlow/chooseProcessFlow.vue'
import chooseMaterialChildren from '@/views/engineeringManage/BOMManage/chooseMaterialChildren.vue'
import chooseProcess from './chooseProcess.vue'
const _ = require('lodash')
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {},
    tag: {},
    tagId: {}
  },
  data() {
    return {
      flatArray: [],
      engineeringProcessNameIndex: 1,
      engineeringProcessName: '',
      productBySelf: '1',
      toInspect: '1',
      toWms: '1',
      requisitionOrReturnList: [
        { label: '否', value: '0' },
        { label: '是', value: '1' }
      ],
      currentmaterial: '',
      treeData: [],
      checkedKeys: [],
      currentNodeKey: undefined,
      currentNodeEL: undefined,

      currentNodeData: {
        engineeringProcessName: '',
        engineeringProcessId: '',
        engineeringRequirementProcess: []
      },
      loading: true,
      isShow: true,
      formData: {
        id: undefined,
        code: undefined,
        bomDetailId: undefined,
        materialId: undefined,
        materialCode: undefined,
        materialName: undefined,
        materialModel: undefined,
        materialTypeName: undefined,
        materialUnitName: undefined,
        flowId: undefined,
        flowCode: undefined,
        fileName: '',
        fileRealName: '',
        fileUrl: '',
        remark: undefined,
        isEqual: '0',
        versionCode: ''
      },
      rules: {
        code: [
          { required: true, message: '工艺要求编码不能为空', trigger: 'blur' }
        ],
        materialCode: [
          { required: true, message: '物料编码不能为空', trigger: 'change' }
        ],
        flowCode: [
          { required: true, message: '工艺流程号不能为空', trigger: 'change' }
        ],
        versionCode: [
          { required: true, message: '版本号不能为空', trigger: 'change' }
        ],
        isEqual: [
          { required: true, message: '生产数量是否必须等于计划数量不能为空', trigger: 'change' }
        ]
      },
      processFlowList: [], // 左边工艺流程列表数据

      detailForm: {}, // 计时，计件数据
      detailFormTemplate: { // 计时，计件数据的模板（初始化的时候用）
        flowDetailId: '',
        standardWorkTime: '',
        workTimePrice: '',
        unitPriceOfPiecework: ''
      },
      tableData1: [], // 生产输入数据
      tableData2: [], // 生产输出数据
      tableData3: [], // 生产输出数据

      selectionsAll1: [], // 生产输入选中值
      selectionsAll2: [], // 生产输出选中值
      selectionsAll3: [], // 生产输出选中值

      currentProcess: {}, // 左边当前选中工序
      currentProcessIndex: '', // 左边当前选中工序序号
      currentChooseType: '', // 当前选择物料的类型（生产输入/生产输出），目的是共用同一个物料选择弹框

      pictureOptions: [], // 图号下拉数据

      triggerTag: false // 触发标志，watch是否触发
    }
  },
  watch: {
    'formData.flowId'(data) {
      if (this.triggerTag && data) {
        // 通过工艺流程ID，获取工艺流程明细
        getProcessList(data).then(res => {
          if (res.data.data.length > 0) {
            const cacheData = res.data.data
            cacheData.forEach(item => {
              item.processFlowDetailId = item.id
              item.flowDetailId = item.id
              delete item['id']
            })
            this.processFlowList = cacheData

            this.$nextTick(() => {
              this.initProcessFlowData()
            })
          } else {
            this.$message({
              message: '工艺流程数据不存在',
              type: 'warning'
            })
          }
        })
      }
    }
  },
  mounted() {
    // if (this.tag == 'add') { // 新增
    //   this.isShow = true
    //   this.loading = false
    // }
    if (this.tag == 'edit') { // 编辑
      this.getInfo()
    }
    if (this.tag == 'copy') { // 复制)
      getInfoYg(this.tagId).then(res => {
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        this.formData.id = ''
        this.formData.code = '自动生成'
        this.formData.versionCode = ''
        this.$refs.form.clearValidate('versionCode')
        this.removeIdsTreeId(res.data.data)
        this.treeData = res.data.data
        console.log(this.treeData)
        this.$nextTick(() => {
          document.querySelector('.el-tree-node__content').click()
        })
      })
    }
  },
  methods: {
    //
    findParentIds(tree, childId, nodeKey, result = []) {
      for (const node of tree) {
        if (node.materialId === childId && node.nodeKey == nodeKey) {
          return result
        }
        if (node.children) {
          result.push(node.materialId)
          const parentIds = this.findParentIds(node.children, childId, nodeKey, result)
          if (parentIds.length > 0) {
            return parentIds
          }
          result.pop()
        }
      }
      return []
    },
    setTreeIndex(arr, index) {
      for (let i = 0; i < arr.length; i++) {
        const currentIndex = index + 1
        arr[i] = { ...arr[i], engineeringProcessNameIndex: currentIndex }
        if (arr[i].children && arr[i].children.length > 0) {
          this.setTreeIndex(arr[i].children, currentIndex)
        }
      }
    },
    removeIdsTreeId(nodes) {
      for (let i = 0; i < nodes.length; i++) {
        const node = nodes[i]
        delete node.id // 删除当前节点的id属性
        if (node.children && node.children.length > 0) {
          this.removeIdsTreeId(node.children) // 递归删除子节点的id属性
        }
      }
    },
    chooseProcessCallback(row) {
      if (this.currentNodeData.engineeringProcessId && row.id == this.currentNodeData.engineeringProcessId) {
        this.currentNodeData.engineeringProcessName = ''
        this.currentNodeData.engineeringProcessId = ''
        this.currentNodeData['currentmaterial'] = ''
        this.engineeringProcessName = ''
        this.$message.success('工序已置空')
        return
      }

      this.currentNodeData['currentmaterial'] = row.name
      this.engineeringProcessName = row.name
      this.currentNodeData.engineeringProcessName = row.name
      this.currentNodeData.engineeringProcessId = row.id
    },
    chooseProcess() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: chooseProcess, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: { id: this.currentNodeData.engineeringProcessId, name: this.currentNodeData.engineeringProcessName }
          }
        },
        area: ['880px', '700px'],
        title: '选择工序', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    treeNodeClick(data, node, el) { // 点击树节点
      if (this.currentNodeKey == data.nodeKey) {
        console.log(this.currentNodeKey)
        return
      }
      let tag = true
      if (this.formData.materialId !== data.materialId || this.currentNodeKey !== undefined) {
        if (tag && this.tableData1.length > 0 && this.tableData1.filter(item => !item.demandNumber).length > 0) {
          this.$message({
            message: '需求数量不能为空',
            type: 'warning'
          })
          tag = false
        }
        if (tag && this.tableData1.length > 0 && this.tableData1.filter(item => !this.SETTINGS.reg_no_zero.test(item.demandNumber)).length > 0) {
          this.$message({
            message: '需求数量错误',
            type: 'warning'
          })
          tag = false
        }
        if (tag && !this.engineeringProcessName && this.tableData1.length > 0) {
          this.$message({
            message: '工序不能为空',
            type: 'warning'
          })
          tag = false
        }
      }
      if (tag && !this.checkCurrentForm()) {
        tag = false
        return
      }
      if (tag) {
        this.currentNodeData.children = this.tableData1
        this.currentNodeKey = node.data.nodeKey
        this.currentNodeEL = el
        this.currentNodeData = data
        this.engineeringProcessId = this.currentNodeData.engineeringProcessId ? this.currentNodeData.engineeringProcessId : ''
        this.engineeringProcessName = this.currentNodeData.engineeringProcessName ? this.currentNodeData.engineeringProcessName : ''
        this.currentNodeData['currentmaterial'] = data.engineeringProcessName ? data.engineeringProcessName : ''
        this.productBySelf = this.currentNodeData.productBySelf ? this.currentNodeData.productBySelf : '1'
        this.toInspect = this.currentNodeData.toInspect ? this.currentNodeData.toInspect : '1'
        this.toWms = this.currentNodeData.toWms ? this.currentNodeData.toWms : '1'
        this.currentNodeData.engineeringRequirementProcess = this.currentNodeData.engineeringRequirementProcess ? this.currentNodeData.engineeringRequirementProcess : []
        this.tableData2 = [data]
        this.tableData1 = data.children ? data.children : []
      } else {
        console.log(2222)
        this.currentNodeEL.$el.click()
      }
    },
    setFileName2(...data) {
      this.currentNodeData.engineeringRequirementProcess[data[3]].fileName = data[0]
      this.currentNodeData.engineeringRequirementProcess[data[3]].fileRealName = data[1]
      this.currentNodeData.engineeringRequirementProcess[data[3]].fileUrl = data[2]
    },
    setFileName(...data) {
      this.$set(this.formData, 'fileName', data[0])
      this.$set(this.formData, 'fileRealName', data[1])
      this.$set(this.formData, 'fileUrl', data[2])
    },
    headerCellClassName(data) {
      if (['demandNumber', 'requisitionOrReturnList'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    checkCurrentForm() { // 校验当前工序的表单
      let res = true
      if (res && (this.currentNodeData.standardWorkTime)) {
        if (!this.SETTINGS.reg_integer.test(this.currentNodeData.standardWorkTime)) {
          this.$message({
            message: '工时必须为整数',
            type: 'warning'
          })
          res = false
        }
      }
      if (res && (this.currentNodeData.workTimePrice)) {
        if (!this.SETTINGS.reg_zero.test(this.currentNodeData.workTimePrice)) {
          this.$message({
            message: '工时单价未正确填写',
            type: 'warning'
          })
          res = false
        }
      }
      if (res && (this.currentNodeData.unitPriceOfPiecework)) {
        if (!this.SETTINGS.reg_zero.test(this.currentNodeData.unitPriceOfPiecework)) {
          this.$message({
            message: '计件单价未正确填写',
            type: 'warning'
          })
          res = false
        }
      }
      if (res) {
        return true
      } else {
        return false
      }
    },
    chooseMaterialChildrenCallBack(rowList) {
      console.log(rowList)
      if (!rowList) {
        return
      }
      this.tableData1 = []
      const cacheTableData = []
      rowList.forEach(item => {
        if (!item.requisitionOrReturn && item.requisitionOrReturn != '0') {
          this.$set(item, 'requisitionOrReturn', '1')
        }
        if (!this.tableData1.some(item2 => item2.materialId == item.materialId)) {
          delete item['id']
          cacheTableData.push(item)
          // 把当前操作完的数据保存到树结构中
          item.nodeKey = Date.now() + Number(_.uniqueId()) // 生成唯一ID，作为node key
          this.$refs.tree.append(item, this.currentNodeKey)
        } else {
          cacheTableData.push((this.tableData1.filter(item2 => item2.materialId == item.materialId))[0])
        }
      })
      this.$nextTick(() => {
        this.tableData1 = cacheTableData
        this.handleNumberChange()
      })
    },
    handleNumberChange() {
      this.$refs.tree.updateKeyChildren(this.currentNodeKey, this.tableData1)
    },
    chooseProduceIn() {
      console.log(this.findParentIds(this.treeData, this.currentNodeData.materialId))
      this.$layer.iframe({
        // 弹框
        content: {
          content: chooseMaterialChildren, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: this.tableData1,
            excludeSelect: [...this.findParentIds(this.treeData, this.currentNodeData.materialId, this.currentNodeData.nodeKey), this.currentNodeData.materialId]
          } // 当前主物料和当前点击的父级物料不能勾选
        },
        area: ['1320px', '700px'],
        title: '选择物料', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    deleteProduceIn() {
      const data = this.$deepClone(this.tableData1)
      this.selectionsAll1.forEach(item => {
        data.splice(data.indexOf(item), 1)
      })
      this.tableData1 = data
      this.handleNumberChange()
    },
    chooseProduceProcess() {
      const row = {
        operationDescription: '',
        productCharacter: '',
        courseCharacter: '',
        fileName: '',
        fileRealName: '',
        fileUrl: ''
      }
      this.currentNodeData.engineeringRequirementProcess.push(row)
    },
    deleteProduceProcess() {
      this.selectionsAll3.forEach(item => {
        this.currentNodeData.engineeringRequirementProcess.splice(this.currentNodeData.engineeringRequirementProcess.indexOf(item), 1)
      })
    },
    selectionChange1(row) {
      this.selectionsAll1 = row
    },
    selectionChange2(row) {
      this.selectionsAll2 = row
    },
    selectionChange3(row) {
      this.selectionsAll3 = row
    },
    getInfo() {
      getInfoYg(this.tagId).then(res => {
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        this.treeData = res.data.data
        this.setTreeIndex(this.treeData, 0)
        this.$nextTick(() => {
          document.querySelector('.el-tree-node__content').click()
        })
      })
    },
    flatArr(arr) {
      for (let i = 0; i < arr.length; i++) {
        this.flatArray.push(arr[i])
        if (arr[i].children && arr[i].children.length > 0) {
          arr[i]['hasChildren'] = '0'
          this.flatArr(arr[i].children)
        } else {
          arr[i]['hasChildren'] = '1'
        }
      }
    },
    onSubmit(e) {
      console.log(this.treeData)
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.tableData1.length > 0 && this.tableData1.filter(item => !item.demandNumber).length > 0) {
            this.$message.warning('需求数量不能为空')
            return
          }
          if (this.tableData1.length > 0 && this.tableData1.filter(item => !this.SETTINGS.reg_no_zero.test(item.demandNumber)).length > 0) {
            this.$message({
              message: '需求数量错误',
              type: 'warning'
            })
            return
          }
          if (this.checkCurrentForm()) {
            // 如果校验通过，先把旧数据更新到左边工序列表中
            // this.setTreeIndex(this.treeData, 0)
            const cacheData = this.$deepClone(this.formData)
            cacheData.data = this.$deepClone(this.treeData)
            addOrUpdate({ ...cacheData, status: e }).then(res => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.$layer.close(this.layerid) // 关闭弹框
              this.$parent.refresh() // 调用父组件的刷新方法
            }).catch(() => {
              console.log(1111)
              this.currentNodeEL.$el.click()
            })
          }
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },

    chooseMaterial() {
      this.triggerTag = true
      this.$layer.iframe({
        // 弹框
        content: {
          content: chooseMaterial, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: this.formData
          }
        },
        area: ['1000px', '700px'],
        title: '选择物料', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    chooseMaterialCallBack(row) {
      this.treeData = []
      this.formData.materialId = row.materialId
      this.formData.materialCode = row.materialCode
      this.formData.materialName = row.materialName
      this.formData.materialModel = row.materialModel
      this.formData.materialTypeName = row.materialTypeName
      this.formData.materialUnitName = row.materialUnitName
      this.treeData = [this.formData]
      // 选中之后的数据手动加一个nodeKey作为树节点的唯一值
      row.nodeKey = Date.now() + Number(_.uniqueId()) // 生成唯一ID，作为node key
      delete row['id']

      // 如果左边物料已经有了，把左边的子物料继承到当前选中的物料下面
      if (this.treeData.length > 0 && this.treeData[0].children && this.treeData[0].children.length > 0) {
        row.children = this.$deepClone(this.treeData[0].children)
      }

      this.treeData = [row]
      this.setTreeIndex(this.treeData, 0)
      this.$nextTick(() => {
        document.querySelector('.tree_container .el-tree-node__content').click()
        this.initProcessFlowData(row)
      })
    },
    initProcessFlowData(data) { // 初始化
      this.currentNodeData['productBySelf'] = '1'
      this.currentNodeData['toInspect'] = '1'
      this.currentNodeData['toWms'] = '1'
      this.tableData1 = []
      this.tableData2 = [data]
      this.tableData3 = []
    }
  },
  chooseProcessFlow() {
    this.triggerTag = true
    this.$layer.iframe({
      // 弹框
      content: {
        content: ChooseProcessFlow, // 传递的组件对象
        parent: this, // 当前的vue对象
        data: {
          id: this.formData.flowId ? this.formData.flowId : ''
        }
      },
      area: ['880px', '700px'],
      title: '选择工艺流程', // 标题
      shadeClose: false // 点击遮罩是否关闭
    })
  }
}

</script>

<style lang="less" scoped>
.detail_form_item_radio{
  /deep/ .el-radio__label{
    display: inline-block;
  }
}
.bitian::before{
  content: '*';
  color: red;
  margin-right: 4px;
}
.detail_form_item{
.clickChoose {
  margin: 10px 0;
  width: calc(50% - 120px);
    height: 30px;
    line-height: 30px;
        display: flex;
        .clickChoose_button {
          width: 30px;
          background-color: rgba(56, 123, 252, 1);
          display: flex;
          justify-content: center;
          align-items: center;
          color: white;
          border-radius: 0 4px 4px 0;
        }

        .clickChoose_button:hover {
          background-color: rgba(56, 123, 252, 0.5);
        }
      /deep/ .el-input__inner {
        height: 30px;
        border-radius: 4px 0 0 4px;
      }
    }
}

        /deep/ .el-radio__label{
          min-width: 70px !important;
        }
    .tree_container{
      margin: 0 20px;
      overflow-x: auto;
      width: calc(100% - 40px);
      /deep/ .el-tree-node__content{
        height: 40px;
        .tree-node{
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          width: 100%;
          // flex: 1;
          // display: flex;justify-content: space-between;align-items: center;
        }
        .node_operate{
          display: flex;align-items: center;
          .node_operate_item{
            display: flex;justify-content: center;align-items: center;
            margin-right: 20px;
          }
        }
        .el-tree-node__children{
          background-color: transparent;
        }

      }
      /deep/ .el-tree-node__children{
        min-width: fit-content;
      }

      /deep/ .el-tree-node__content:hover{
        background-color: rgba(56,123,252,0.5);
        color: white;
      }
    }
.bom_bottom{
  display: flex;
  border-top: 1px solid rgba(105,105,105,0.2);
  .bom_bottom_tree{
    width: 30%;
    border-right: 1px solid rgba(105,105,105,0.2);
    .tree_header{
      height: 50px;
      margin: 0 20px;
      display: flex;align-items: center;
      font-size: 14px;
      color: #333333;
      border-bottom: 1px solid #387BFC;
    }

  }
  .bom_bottom_detail{
    width: 70%;
    .formItem_header_padding{
      margin-top: 3px;
    }
  }
}
.processRequirement_bottom{
  display: flex;
  border-top: 1px solid rgba(105,105,105,0.2);
  .processRequirement_bottom_tree{
    width: 30%;
    border-right: 1px solid rgba(105,105,105,0.2);
    .tree_header{
      height: 50px;
      margin: 0 20px;
      display: flex;align-items: center;
      font-size: 14px;
      color: #333333;
      border-bottom: 1px solid #387BFC;
    }
    .tree_container{
      margin: 0 20px;overflow-y: overlay;

      .tree_container_item{
        // width: 100%;
        height: 40px;display: flex;align-items: center;
        padding-left: 20px;
      }
      .selected_row{

        background-color: rgba(56,123,252,1);
        color: white;
      }

      // .tree_container_item:hover{
      //   background-color: rgba(56,123,252,0.5);
      //   color: white;
      // }
    }
  }
  .processRequirement_bottom_detail{
    width: 70%;
    .formItem_header_padding{
      margin-top: 20px;
    }
    .detail_form{
      display: flex;align-items: center;
      flex-wrap: wrap;
      .detail_form_item_double{
        width: calc(100% - 40px);
        display: flex;align-items: center;
        margin-left: 20px;
        margin-right: 20px;
        .detail_form_item_name{
          height: 30px;
          line-height: 30px;
          width: 120px;
          font-size: 14px;
          color: #666;
        }
        .detail_form_item_radio{
          width:calc(100% - 120px);
        }
      }
      .detail_form_item{
        width: calc(50% - 40px);
        display: flex;align-items: center;
        margin-left: 20px;
        margin-right: 20px;
        .detail_form_item_name{
          height: 30px;
          line-height: 30px;
          width: 120px;
          font-size: 14px;
          color: #666;
        }

        .detail_form_item_radio{
          width: calc(100% - 120px);
        }
        .detail_form_item_input{
          width: calc(100% - 120px);
          /deep/ .el-input__inner{
            height: 30px;
            line-height: 30px;
          }
        }
      }
    }
  }
}
</style>
